from data_access.database import Session
from sqlalchemy.exc import SQLAlchemyError

from data_access.models.models import Database


class DatabaseDAO:
    def __init__(self):
        self.session = Session()

    def add_database(self, dispatch_code, database_id, database_type, database_name, database_host, database_port,
                     database_username, database_password, database_extra_parameter=None, database_driver=None, comment=None):
        new_database = Database(
            dispatch_code=dispatch_code,
            database_id=database_id,
            database_type=database_type,
            database_name=database_name,
            database_host=database_host,
            database_port=database_port,
            database_username=database_username,
            database_password=database_password,
            database_extra_parameter=database_extra_parameter,
            database_driver=database_driver,
            comment=comment
        )
        try:
            self.session.add(new_database)
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()

    def get_database_by_database_id(self, dispatch_code, database_id):
        try:
            return self.session.query(Database).filter(Database.dispatch_code == dispatch_code, Database.database_id == database_id).first()
        except SQLAlchemyError as e:
            return None
        finally:
            self.session.close()

    def update_database(self, database_id, **kwargs):
        try:
            self.session.query(Database).filter(Database.database_id == database_id).update(kwargs)
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()

    def delete_database(self, database_id):
        try:
            self.session.query(Database).filter(Database.database_id == database_id).delete()
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()
